<?php
/**
 * Created by PhpStorm.
 * User: cnsecer
 * Date: 15/2/25
 * Time: 下午6:17
 */

namespace common;

use backend\models\CategoryManager;
use backend\models\Setting;
use common\models\Blacklist;
use common\models\Category;
use common\models\Comment;
use common\models\Post;
use common\models\User;
use common\models\UserPost;
use common\models\UserCategory;
use common\models\ZancaiComment;
use common\models\ZancaiPost;
use yii\helpers\Html;

class Yii01
{
    public static function dd($data)
    {
        echo "<pre>";
        print_r($data);
        echo "</pre>";
    }

    public static function tree($array, $child = "child", $pid = null)
    {
        $temp = [];
        foreach ($array as $v) {
            if ($v['pid'] == $pid) {
                $v[$child] = self::tree($array, $child, $v['id']);
                $temp[] = $v;
            }
        }
        return $temp;
    }

    /**
     * 获取用户关注的分类
     * @param $uid
     * @return array|\yii\db\ActiveRecord[]
     */
    public static function getUserCategory($uid, $limit = 10)
    {
        $cate = Category::find()
            ->innerJoinWith('userCategories')
            ->where(['user_category.user_id' => $uid])
            ->asArray()
            ->limit($limit)
            ->orderBy(['user_category.time' => SORT_ASC])
            ->all();
        return $cate;
    }

    /**根据分类ID获取当前分类文章总数
     * @param $cid
     * @return int|string
     */

    public static function getCategoryPostCount($cid)
    {
        $post = Post::find()
            ->where(['cate_id' => $cid])
            ->count();
        return $post;
    }

    /**
     * 获取用户关注的文章
     * @param $uid
     * @return array|\yii\db\ActiveRecord[]
     */
    public static function getFocusPost($uid, $limit = 5)
    {
        $post = Post::find()
            ->innerJoinWith('userPosts')
            ->innerJoinWith("cate")
            ->where(['user_post.user_id' => $uid])
            ->asArray()
            ->limit($limit)
            ->all();
        return $post;
    }

    /**
     * 根据类型获取用户发布的文章
     * @param $uid
     * @param $type
     * @param int $limit
     * @return array|\yii\db\ActiveRecord[]
     */
    public static function getUserPostByType($uid, $type, $limit = 5)
    {
        $post = Post::find()
            ->where(['user_id' => $uid, 'type' => $type])
            ->limit($limit)
            ->all();
        return $post;
    }

    /**获取登录用户某个字段的信息
     * @param $field
     * @return mixed
     */
    public static function getUserInfo($field)
    {
        $user = User::findOne(\Yii::$app->user->id);
        return $user[$field];
    }

    /**判断用户是不是当前分类的版主
     * @param $uid
     * @param $cid
     * @return static
     */
    public static function isManager($uid, $cid)
    {
        return CategoryManager::findOne(['cate_id' => $cid, 'user_id' => $uid]);
    }

    /**
     * 获取用户管理的板块
     * @param $uid
     * @return array|\yii\db\ActiveRecord[]
     */
    public static function getManagerCategory($uid)
    {
        return CategoryManager::find()
            ->innerJoinWith('cate')
            ->orderBy(['category.sort'=>SORT_DESC])
            ->where(['user_id' => $uid])
            ->asArray()
            ->all();
    }

    /**
     * 根据用户id获取用户收藏的文章总数
     * @param $uid
     * @return int|string
     */
    public static function getCollectPostNum($uid)
    {
        return UserPost::find()->where(['user_id' => $uid])->count();
    }

    /**
     * 根据用户ID获取对应类型的文章总数
     * @param $uid
     * @param $type
     * @return int|string
     */
    public static function getUserPostNumByType($uid, $type)
    {
        return Post::find()->where(['user_id' => $uid, 'type' => $type])->count();
    }

    /**判断是否为相邻两天  传入Ymd 格式的时间即可
     * @example isAdjacentDay("20150307","20150308")
     * @param $last
     * @param $current
     * @return bool
     * @author cnsecer.com
     */
    public static function isStreakDays($last_date, $this_date)
    {
        self::dd($last_date);
        self::dd($this_date);
        if (($last_date['year'] == $this_date['year']) && ($this_date['yday'] - $last_date['yday'] == 1)) {
            return true;
        } elseif (($this_date['year'] - $last_date['year'] == 1) && ($last_date['mon'] - $this_date['mon'] == 11) && ($last_date['mday'] - $this_date['mday'] == 30)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 截取指定长度的字符串
     * @param $string
     * @param $sublen
     * @param int $start
     * @param string $code
     * @return string
     */
    public static function cutStr($string, $sublen, $start = 0, $code = 'utf-8')
    {
        $string = strip_tags(htmlspecialchars_decode($string));
        if ($code == 'utf-8') {
            $pa = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/";
            preg_match_all($pa, $string, $t_string);
            if (count($t_string[0]) - $start > $sublen) return join('', array_slice($t_string[0], $start, $sublen)) . "...";
            return join('', array_slice($t_string[0], $start, $sublen));
        } else {
            $start = $start * 2;
            $sublen = $sublen * 2;
            $strlen = strlen($string);
            $tmpstr = '';
            for ($i = 0; $i < $strlen; $i++) {
                if ($i >= $start && $i < ($start + $sublen)) {
                    if (ord(substr($string, $i, 1)) > 129) {
                        $tmpstr .= substr($string, $i, 2);
                    } else {
                        $tmpstr .= substr($string, $i, 1);
                    }
                }
                if (ord(substr($string, $i, 1)) > 129) $i++;
            }
            //超出多余的字段就显示...
            if (strlen($tmpstr) < $strlen) $tmpstr .= "...";
            return $tmpstr;
        }
    }

    /**
     * 递归输出多维数组
     * @param $array
     */
    public static function traverseArray($array,$uid)
    {
        $weburl = \Yii::$app->urlManager->baseUrl;
        foreach ($array as $v) {
            $zan = self::commentZC(\Yii::$app->request->getUserIP(), $v['id'], 0);
            $cai = self::commentZC(\Yii::$app->request->getUserIP(), $v['id'], 1);
            $str1 = "";
            $str2 = "";
            if ($zan) {
                $str1 = 'active';
            }
            if ($cai) {
                $str2 = 'active';
            }
            $fuck ="";
            if($v['user_id'] == $uid){
                $fuck ="(<b style='color: red'>PO主</b>)";
            }
            $html1 = <<<CODE
            <ul class="media-list comment_box">
            <li class="media">
                <div class="media-left media-left0">
                    <!-- 点赞双箭头 -->
                    <div class="midcol unvoted">
                        <a  href="javascript:;"  class="{$str1} comment-zan" data-id="{$v['id']}" >
                        <b class="glyphicon glyphicon-chevron-up"></b><br>
                        <span class="num">{$v['zan']}</span>
                        </a>
                        <a  href="javascript:;"  class="{$str2} comment-cai" data-id="{$v['id']}" >
                        <span class="num">{$v['cai']}</span><br>
                        <b class="glyphicon glyphicon-chevron-down"></b>
                        </a>
                    </div>
                    <!-- 点赞双箭头 -->
                </div>

                <div class="media-left fold_box">
                    <a href="javascript:;" class="zhedie">
                        <img class="media-object img-rounded" src="{$weburl}/{$v["img"]}">
                    </a>

                </div>

                <div class="media-body">
                    <div class="gbook_list">
                        <a href="javascript:;" name="comment{$v["id"]}" class="nickname">{$v["user"]}{$fuck}</a><em>&nbsp;{$v["signature"]}&nbsp;</em>
                    </div>
                    <div class="content">{$v["content"]}</div>
                    <div class="comment-bottom">
                        <a href="javascript:;" id="report-comment"><span class="glyphicon glyphicon-trash"></span> 举报 <i style="display:none">{$v['id']}</i></a>
                        <a href="javascript:;" id="replay-comment" data-replay="{$v['user']}"   data-form="form-{$v['id']}"><span class="glyphicon glyphicon-comment"></span> 回复 </a>
CODE;
            echo $html1;
            if (\Yii::$app->user->can('admin_login') || self::isManager(\Yii::$app->user->id, self::getCateIdByPostId($v['post_id']))) {
                echo '<a href="javascript:;" class="delete-comment" data-id="' . $v['id'] . '"> <span class="glyphicon glyphicon-remove-circle" style="color:red;"></span>  删除 </a>';
            }
            echo "<span><i class='glyphicon glyphicon-time'></i>  发表于" . self::diffTime($v['time']) . "前</span>";
            $html2 = <<<CODE
                    </div>
                    <div class="clearfix"></div>
                    <form class="replay-from" id="form-{$v['id']}">
                            <div class="form-group">
                                <textarea   cols="5" class="form-control"></textarea>
                            </div>
                            <div class="form-group">
                                <div class="row">
                                    <div class="col-md-1 col-md-offset-9">
                                        <a href="javascript:;" class="btn btn-default" id="cancel-replay" data-form="form-{$v['id']}">取消</a>
                                    </div>
                                    <div class="col-md-1">
                                        <a href="javascript:;" class="btn btn-success" id="submit-replay" data-form="form-{$v['id']}" data-reply="{$v['user_id']}" data-post={$v['post_id']} data-pid="{$v['id']}">确定</a>
                                    </div>
                                </div>
                            </div>
                    </form>
                </div>

            </li>
CODE;

            echo $html2;
            if ($v['child']) {
                self::traverseArray($v['child'],$uid);
            }
            echo '</ul>';


        }

    }

    /**
     * 获取时间差
     * @param $time
     * @return string
     */
    public static function diffTime($time)
    {
        $date = floor((time() - $time) / 86400);
        $hour = floor((time() - $time) % 86400 / 3600);
        $minute = floor((time() - $time) % 86400 / 60);
        $second = floor((time() - $time) % 86400) + 1;

        if ($date) {
            return $date . "天";
        }
        if ($hour) {
            return $hour . "小时";
        }
        if ($minute) {
            return $minute . "分钟";
        }
        if ($second) {
            return $second . "秒";
        }
    }

    public static function diffTime2($time)
    {
        $date = floor(($time - time()) / 86400);
        $hour = floor(($time - time()) % 86400 / 3600);
        $minute = floor(($time - time()) % 86400 / 60);
        $second = floor(($time - time()) % 86400) + 1;

        if ($date) {
            return $date . "天";
        }
        if ($hour) {
            return $hour . "小时";
        }
        if ($minute) {
            return $minute . "分钟";
        }
        if ($second) {
            return $second . "秒";
        }
    }

    /**
     * 获取文章内图片
     * @param $thumb
     * @param $url
     * @param $content
     * @return string
     */
    public static function getThumb($thumb, $url, $content)
    {
        //如果有缩略图 则返回
        if ($thumb) {
            if ($thumb != "") {
                if(strstr($thumb,"http")){
                    return $thumb;
                }
                return "/".$thumb;
            }
            return false;
        }
//        if ($url) {
//            $match = self::getRemoteImage($url);
//            if ($match[1]) {
//                return $match[1];
//            }
//            return "";
//        }
        //如果没有 就截取文章的第一张图片
        // return "img/nothumb.jpg";
        preg_match("<img.*src=[\"](.*?)[\"].*?>", $content, $match);
        if ($match) {
            $len = count($match);
            $key = floor($len/2);
            $return =  $match[intval($key)];
            if(strstr($return,"baidu") || strstr($return,"baidu") ){
                if(!strstr($match[$len-1],"baidu")){
                    return $match[$len-1];
                }

                return "";
            }
            return $match[intval($key)];
        } else {
            return "";
        }
    }

    /**
     * 获取文章评论数
     * @param $id
     * @return int|string
     */
    public static function getComments($id)
    {
        $num = Comment::find()
            ->where(['post_id' => $id])
            ->count();
        return $num;
    }

    /**
     * 获取用户评论数量
     * @param $uid
     * @return int|string
     */
    public static function getUserComments($uid)
    {
        $num = Comment::find()
            ->where(['user_id' => $uid])
            ->count();
        return $num;
    }

    /**
     * 用户是否被封禁
     * @param int $type
     * @return string
     */
    public static function isBlackList($type = 1)
    {
        if ($type == 1 && \Yii::$app->user->id) {
            $user = User::findOne(\Yii::$app->user->id);
            $data = Blacklist::findOne(['username' => $user->username]);
            if ($data) {
                $diff = self::diffTime2(strtotime($data->time));
                return $diff;
            }

        } else {
            $data = Blacklist::findOne(['ip_address' => \Yii::$app->request->getUserIP()]);
            if ($data) {
                $diff = self::diffTime2(strtotime($data->time));
                return $diff;
            }

        }

    }

    /**弹窗
     * @param $msg
     */
    public static function alert($msg)
    {
        $html = <<<SB

<script>
    alert("账号被封禁,离解封还有{$msg}");
</script>
SB;
        echo $html;
    }

    /**
     * 获取站点信息
     * @param $field
     * @return static
     */
    public static function getSiteInfo($field)
    {
        return Setting::findOne(['key' => $field]);
    }

    /**判断用户是否订阅当前分类
     * @param $cid
     * @return static
     */
    public static function isDingyue($cid)
    {
        return UserCategory::findOne(['user_id' => \Yii::$app->user->id, 'cate_id' => $cid]);

    }

    /**
     * 获取网页标题
     * @param $url
     * @return bool|mixed
     */
    public static function getRemoteTitle($url)
    {
        //判断是否是链接
        $search = '~^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?~i';
        preg_match_all($search, trim($url), $arr);
        // var_dump($arr[1][0]);die;
        if (empty($arr[1][0])) {
            return false;
        }
        //判断链接是否可访问
        $array = get_headers($url);
        if (!preg_match('/200/', $array[0])) {
            return false;
        }
        //获取网页内容
        $html = file_get_contents($url);

        $right = strstr($html, "<title>");
        $left = strstr($right, "</title>", true);
        $temp = str_ireplace("<title>", "", $left);
        return $temp;
    }

    public static function getRemoteImage($url)
    {
        ob_start();
        readfile($url);
        $con = ob_get_contents();
        ob_end_clean();

        //   $con = file_get_contents($url);
        $pattern = "/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png]))[\'|\"].*?[\/]?>/";
        preg_match_all($pattern, $con, $match);
        //  self::dd($match[1]);die;
        return $match[1];
    }


    /**将图片保存到本地
     * @param $url
     * @param string $filename
     * @return bool|string
     */
    public static function GrabImage($url)
    {
        if ($url == "") {
            return false;
        }

        //获取网页内容
        ob_start();
        @readfile($url);
        $con = ob_get_contents();
        ob_end_clean();

        if (!$con) {
            return false;
        }
        //获取图片
        $pattern = "/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png]))[\'|\"].*?[\/]?>/";
        preg_match_all($pattern, $con, $match);
        if(!$match){
            return false;
        }
        $len = count($match);
        if ($len < 2) {
            return false;
        }
        //取出中间的图片并设置新名字
        @$image = $match[1][floor(count($match[1]) / 2)];
        //$image = $match[1][100];
        if ($image) {
            return $image;
        } else {
            return false;
        }
        //不保存到本地了  下面的不再执行

        $ext = strrchr($image, ".");
        $filename = time() . rand(0, 99) . $ext;

        //保存图片
        ob_start();
        readfile($image);
        $img = ob_get_contents();
        ob_end_clean();
        if ($img == null) {
            return false;
        }

        $dir = 'uploads/' . date("Ym");
        if (!file_exists($dir)) {
            mkdir($dir);
        }
        $file_path = $dir . "/" . $filename;


        $fp2 = @fopen($file_path, "a");
        fwrite($fp2, $img);
        fclose($fp2);
        return $file_path;


    }

    /**用户是否关注分类
     * @return bool|static
     */
    public static function isHasCate()
    {
        if (!\Yii::$app->user->isGuest) {
            return UserCategory::findOne(['user_id' => \Yii::$app->user->id]);
        }
        return false;
    }

    /**
     * @param $str
     * @return mixed
     */
    public static function getUrl($str)
    {
        $url_arr = explode('/', $str);
        return $url_arr[2];
    }

    public static function getCateIdByPostId($post_id)
    {
        $data = Post::findOne($post_id);
        return $data->cate_id;
    }

    public static function getCateNameByPostId($post_id)
    {
        $data = Post::findOne($post_id);
        return Category::findOne($data->cate_id)->name;
    }

    public static function isUrlCanOpen($url)
    {
        ob_start();
        @readfile($url);
        $img = ob_get_contents();
        ob_end_clean();

        return $img;
    }


    public static function postZC($ip, $post_id, $type)
    {
        return ZancaiPost::findOne([
            'ip_address' => $ip,
            'post_id' => $post_id,
            'type' => $type,
        ]);
    }

    public static function commentZC($ip, $comment_id, $type)
    {
        return ZancaiComment::findOne([
            'ip_address' => $ip,
            'comment_id' => $comment_id,
            'type' => $type,
        ]);
    }

    public static function getReplayNum()
    {
        $uid = \Yii::$app->user->id;
        $count = Comment::find()->where(['reply_to'=>$uid,'msgstatus'=>0])->count();
        return $count;
    }

    public static function getCatePostNum($id)
    {
        return Post::find()->where(['cate_id'=>$id])->count();
    }

    public static function getHotPost($num)
    {
        $query = Post::find()->orderBy(['last_comment' => SORT_DESC])->limit($num)->asArray()->all();

        return $query;
    }
}